import * as React from "react";
import { Button, TreeSelect,Modal ,DatePicker } from "antd";
import { getfindFilesBuildList } from "../../../ServeApi";
import moment from "moment";

// import EleAndWater from "../../../../../../compontents/EleAndWater";
import { AjaxData } from "../../../../../../data/interface/publicInterface";
import DayOrHourTimePicker from "../DayOrHourTimePicker";
import { formattingTreeSelectTreeData } from "../../../../../../utils/common";

import "./index.less";
const RangePicker:any= DatePicker.RangePicker;

export interface CalcConditionProps {
  onChange: (paramJson: CalcConditionParam) => any;
  query: (paramJson: CalcConditionParam,mode:string) => any;
}

export interface CalcConditionState {
  mode:string,
  loading:boolean
}

export interface CalcConditionParam {
  energyType: number;
  buildId: string;
  timeType: number;
  startData: string;
  endData: string;
}

class CalcCondition extends React.Component<
  CalcConditionProps,
  CalcConditionState
> {
  public paramJson: CalcConditionParam = {
    energyType: 1,
    buildId: "",
    timeType: 2,
    startData: ""+moment().add(-3, "day").valueOf(),
    endData: ""+moment().valueOf(),
  };
  public treeData:any[] = [
  {
    title: 'Node1',
    value: '0-0',
    children: [
      {
        title: 'Child Node1',
        value: '0-0-1',
      },
      {
        title: 'Child Node2',
        value: '0-0-2',
      },
    ],
  },
  {
    title: 'Node2',
    value: '0-1',
  },
]
private buildAllArr: any[] = []; //所有节点
private leafArr: any[] = []; //所有叶子节点
private treeSelectData: any[] = [];
private mod:string = "sum";
  state={
    mode:"sum",
    loading:false
  }
  render() {
    let arr: any = [];
    if (this.state.mode === "sum") {
      arr.push(
        <>
          <DayOrHourTimePicker
              value={[moment(Number(this.paramJson.startData)), moment(Number(this.paramJson.endData))]}
              onChange={(timeType: number, dateString: string[]) => {
                this.getDate(timeType, dateString);
              }}
            />
        </>
      );
    }else{
      arr.push(<>
      <span style={{ paddingLeft: 26 }}>时间筛选：</span>
        <RangePicker
          value={[moment(Number(this.paramJson.startData)), moment(Number(this.paramJson.endData))]}
          format="YYYY/MM/DD"
          onChange={(date: any) => {
            console.log(date)
            this.paramJson.startData = date[0]
            this.paramJson.endData = date[1]
            this.paramJson.timeType = 3
            this.forceUpdate()
          }}
        />
      </>)
    }
    return (
      <div className="Condition">
        <div className="rowcon_body" style={{ paddingTop: 16 }}>
          <div className="paramRow">
            {/* <EleAndWater
              onChange={(type: number) => {
                this.paramJson.energyType = type;
                this.props.onChange(this.paramJson);
              }}
            /> */}
            <div className="device" style={{ marginRight: '0px',marginLeft:'0px' }}>
              建筑：
              <TreeSelect
                style={{ width: '200px' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={this.treeSelectData}
                placeholder="请选择建筑"
                treeDefaultExpandAll
                onChange={(value) => {
                  this.getBuild(value)
                          }}
              />
            </div>

            {arr}
            <Button
              className="btn"
              type="primary"
              onClick={() => {
                this.props.query(this.paramJson,this.state.mode);
              }}
            >
              查询
            </Button>
          </div>
        </div>
      </div>
    );
  }
  componentWillMount() {
    this.getSelectList();
  }
  getDate(timeType: number, dateString: string[]) {
    this.paramJson.timeType = timeType;
    switch (timeType) {
      case 2:
        if (dateString && dateString[0] && dateString[1]) {
          this.paramJson.startData = ""+moment(
            dateString[0],
            "YYYY/MM/DD HH"
          ).valueOf();
          this.paramJson.endData = ""+moment(dateString[1], "YYYY/MM/DD HH").valueOf();
          
        }
        break;
      case 3:
        if (dateString && dateString[0] && dateString[1]) {
          this.paramJson.startData = ""+moment(
            dateString[0],
            "YYYY/MM/DD"
          ).startOf("day").valueOf();
          this.paramJson.endData = ""+moment(dateString[1], "YYYY/MM/DD HH").endOf("day").valueOf();
          
        }
        break;
      default:
        break;
    }
    console.log(this.paramJson)
    this.props.onChange(this.paramJson);
  }
  getBuild(id){
      this.paramJson.buildId = ""+id;
      
      
      let isleaf = this.isleafNode(id)
      if(isleaf){
        this.setState({
          mode:"mon"
        })
      }else{
        this.setState({
          mode:"sum"
        })
      }
      // console.log("选中的建筑",node,this.mod==="sum"?"查汇总":"查月数据");
      // this.props.onChange(this.paramJson);
  }
  isleafNode(id){
    let isleaf = false
    this.leafArr.map((item:any)=>{
      if(id === item.id){
        isleaf = true
      }
      return item;
    })
    return isleaf
  }
    /**方法函数调用 */
  //格式化树状选择数据
  getTreeData(arr: any[]) {
    let array = arr.map((item) => {
      return {
        key: "" + item.id,
        id: item.id,
        pId: item.parentId,
        value: "" + item.id,
        title: item.name,
      };
    });
    this.buildAllArr = arr;
    this.treeSelectData = formattingTreeSelectTreeData(array);
    this.leafArr = this.getAllLeaf(this.treeSelectData);
    this.forceUpdate();
  }
  // 查询所有叶子节点
  getAllLeaf(data) {
    const result:any[] = []
    function getLeaf(data) {
      data.forEach((item:any) => {
        if (!item.children) {
          result.push(item)
        } else {
          getLeaf(item.children)
        }
      })
    }
    getLeaf(data)
    return result
  }
  /**请求数据 */
  //获取建筑选择项
  async getSelectList(str?: string) {
    let _this = this;
    let pream = {
      name: str ? str : "",
    };
    try {
      
      let res: any = await getfindFilesBuildList(JSON.stringify(pream)).catch(
        (err) => {
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        console.log("树",json.data)
        _this.getTreeData(json.data);
        _this.setState({ loading: false });
        _this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}
export default CalcCondition;
